﻿using aier.dataaccess.model;
using aier.dataaccess.dapper;
using aier.xrm.wcf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Sdk;
using log4net;

namespace aier.business.logic
{
    public class TaskBll
    {
        public TaskDal taskDal { get; set; }
        public CommonWcf commonWcf { get; set; }
        public ILog log { get; set; }
        public ResResult resResult { get; set; }

        /// <summary>
        /// 通过客户id获取任务列表
        /// </summary>
        /// <param name="leadId">客户id</param>
        /// <returns>任务列表</returns>
        public IEnumerable<TaskView> QueryTaskByLeadId(Guid leadId)
        {

            try
            {
                return taskDal.QueryTaskByLeadId(leadId);
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskByLeadId: " + ex.Message);
                return null;
            }

        }

        /// <summary>
        /// 根据负责人id查询任务列表
        /// </summary>
        /// <param name="ownerId">负责人id</param>
        /// <returns>任务列表</returns>
        public IEnumerable<TaskView> QueryTaskByOwnerId(Guid ownerId)
        {
            try
            {
                return taskDal.QueryTaskByOwnerId(ownerId);
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskByOwnerId: " + ex.Message);
                return null;
            }

        }

        /// <summary>
        /// 根据负责人id分页查询任务列表
        /// </summary>
        /// <param name="ownerId">负责人id</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页显示的信息条数</param>
        /// <returns>任务列表</returns>
        public PageResult<TaskView> QueryTaskByOwnerIdPage(Guid ownerId, int pageNum, int pageSize, string orderField)
        {

            try
            {
                var taskView = taskDal.QueryTaskByOwnerIdPage(ownerId, pageNum, pageSize+1, orderField);

                PageResult<TaskView> pageResult = new PageResult<TaskView>();
                pageResult.existsnextdata = taskView.Count() > pageSize;
                pageResult.total = taskDal.QueryTaskByOwnerIdCount(ownerId);
                pageResult.datas = taskView.Skip(0).Take(pageSize).ToList();
                return pageResult;
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskByOwnerIdPage: " + ex.Message + ";OwnerId:" + ownerId.ToString() + ";pageNum:" + pageNum.ToString() + ";pageSize:" + pageSize.ToString());
                return null;
            }
        }
        public PageResult<TaskView> QueryTaskByOwnerIdPage1(Guid ownerId, int pageNum, int pageSize, string orderField)
        {

            try
            {
                var taskView = taskDal.QueryTaskByOwnerIdPage1(ownerId, pageNum, pageSize + 1, orderField);

                PageResult<TaskView> pageResult = new PageResult<TaskView>();
                pageResult.existsnextdata = taskView.Count() > pageSize;
                pageResult.total = taskDal.QueryTaskByOwnerIdCount1(ownerId);
                pageResult.datas = taskView.Skip(0).Take(pageSize).ToList();
                return pageResult;
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskByOwnerIdPage: " + ex.Message + ";OwnerId:" + ownerId.ToString() + ";pageNum:" + pageNum.ToString() + ";pageSize:" + pageSize.ToString());
                return null;
            }
        }

        /// <summary>
        /// 根据客户id分页查询任务列表
        /// </summary>
        /// <param name="ownerId">负责人id</param>
        /// <param name="pageNum">页码</param>
        /// <param name="pageSize">每页显示的信息条数</param>
        /// <returns>任务列表</returns>
        public IEnumerable<TaskView> QueryTaskByLeadIdPage(Guid leadId, int pageNum, int pageSize, string orderField)
        {

            try
            {
                return taskDal.QueryTaskByLeadIdPage(leadId, pageNum, pageSize, orderField);
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskByLeadIdPage: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 根据查询条件查询任务信息集合
        /// </summary>
        /// <param name="ownerid">负责人id</param>
        /// <param name="newLeadname">患者姓名</param>
        /// <param name="newMobile">手机号</param>
        /// <param name="newTel">座机</param>
        /// <returns></returns>
        public PageResult<TaskView> QueryTaskInfoList(Guid ownerid, string condition, int pageNum, int pageSize)
        {
            PageResult<TaskView> pageResult = new PageResult<TaskView>();
            try
            {
                string newLeadname = string.Empty;
                string newMobile = string.Empty;
                string newTel = string.Empty;
           
                if (CommonUtil.IsMobile(condition))
                {
                    //如果为手机
                    newMobile = condition;
                }
                else if (CommonUtil.IsContainChinese(condition))
                {
                    //如果为姓名
                    newLeadname = condition;
                }
                else
                {
                    //否则为座机
                    newTel = condition;
                }
                var taskView =  taskDal.QueryTaskInfoList(ownerid, newLeadname, newMobile, newTel, pageNum, pageSize+1);

                pageResult.existsnextdata = taskView.Count() > pageSize;
                pageResult.total = taskDal.QueryTaskInfoCount(ownerid, newLeadname, newMobile, newTel);
                pageResult.datas = taskView.Skip(0).Take(pageSize).ToList();

                return pageResult;
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskInfoList: " + ex.Message);
                return null;
            }
        }


        /// <summary>
        /// 更新筛查任务信息,必须带有主键
        /// </summary>
        /// <param name="taskInfo"></param>
        public ResResult UpdateTaskInfoById(TaskInfo taskInfo)
        {

            try
            {
                if (taskInfo == null)
                {
                    log.Error("UpdateTaskInfoById 出现错误：传入对象为空");
                    return resResult.FailResult("TaskBll ->UpdateTaskInfoById : 传入实体为空");
                }
                if (Guid.Empty.Equals(taskInfo.Activityid))
                {
                    return resResult.FailResult("TaskBll ->UpdateTaskInfoById : 实体id为空");
                }
                if (taskDal.QueryTaskInfoByTaskId(taskInfo.Activityid) == null)
                {
                    return resResult.FailResult("TaskBll ->UpdateTaskInfoById : 不存在该筛查信息");
                }
                Entity entity = XrmSqlBuilderEx.AsCrmEntity<TaskInfo>(taskInfo);

                commonWcf.UpdateEntityById(entity);
                return resResult.SuccessResult(taskInfo.Activityid);
            }
            catch (Exception e)
            {
                log.Error("UpdateTaskInfoById 出现错误：" + e.Message);
                return resResult.FailResult("TaskBll ->UpdateTaskInfoById Error: " + e.Message);
            }

        }

        /// <summary>
        /// 更新任务实体的系统状态
        /// </summary>
        /// <param name="entityId">实体ID</param>
        /// <param name="statecode">实体状态</param>
        /// <param name="entitylocalName">实体名字</param>
        public ResResult UpdateEntityState(Guid entityId, int statecode, string entitylocalName)
        {
            try
            {
                if (entityId == Guid.Empty)
                {
                    log.Error("UpdateEntityState 出现错误：传入参数为空");
                    return resResult.FailResult("TaskBll ->UpdateEntityState : 传入实体为空");
                }
                if (taskDal.QueryTaskInfoByTaskId(entityId) == null)
                {
                    return resResult.FailResult("TaskBll ->UpdateEntityState : 不存在该筛查信息");
                }
                commonWcf.UpdateStateRequest(entityId, statecode, entitylocalName);
                return resResult.SuccessResult(entityId);
            }
            catch (Exception e)
            {
                log.Error("UpdateEntityState 出现错误：" + e.Message);
                return resResult.FailResult("TaskBll ->UpdateEntityState Error: " + e.Message);
            }

        }

        /// <summary>
        /// 根据任务ID获取任务详情
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public TaskView QueryTaskInfoByTaskId(Guid taskid)
        {
            try
            {
                return taskDal.QueryTaskInfoByTaskId(taskid, true);

            }
            catch (Exception ex)
            {
                log.Error("QueryTaskInfoByTaskId: " + ex.Message);
                return null;
            }

        }

        /// <summary>
        /// 根据任务Id获取筛查信息
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public ScreenNoticeView GetScreenNoticeViewData(Guid taskId,Guid ownerId)
        {
            try
            {
                if (taskId != Guid.Empty)
                {
                    ScreenNoticeView screenNotice = taskDal.GetScreenNoticeData(taskId, ownerId);
                    if (screenNotice != null && screenNotice.screenTeamId!=Guid.Empty)
                    {
                        var screenTeamData = taskDal.GetScreenTeamData(screenNotice.screenTeamId);
                        screenNotice.taskEndData = Convert.ToDateTime(screenNotice.taskEndData).AddHours(8).ToString();
                        screenNotice.screenStartData = Convert.ToDateTime(screenNotice.screenStartData).AddHours(8).ToString();
                        screenNotice.screenTeamName = screenTeamData.Select(x => x.screenTeamName).FirstOrDefault();
                        screenNotice.screenTeamLead = screenTeamData.Select(x => x.ScreenTeamLead).FirstOrDefault();
                        screenNotice.screenGroupMember = string.Join(",", screenTeamData.Select(x => x.screenGroupMember).ToList());
                        return screenNotice;
                    }
                    return screenNotice;
                }
                return null;
            }
            catch (Exception ex)
            {
                log.Error("QueryTaskInfoByTaskId: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 根据Id及实体修改状态
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="entityName"></param>
        /// <param name="state"></param>
        /// <param name="status"></param>
        public void UpdateState(Guid Id,string entityName, int state, int status)
        {
            try
            {
                if (Id != Guid.Empty)
                {
                    commonWcf.UpdateStateRequest(Id, entityName, state, status);
                }
            }
            catch (Exception ex)
            {
                log.Error("UpdateTaskState: " + ex.Message);
                throw ex;
            }
        }
    }
}
